package com.socket.client.handler.command.listener;

import cn.hutool.json.JSONUtil;
import com.socket.client.handler.command.CommandHandler;
import com.socket.core.constant.Topics;
import com.socket.core.model.command.enmus.Group;
import com.socket.core.model.command.topic.GroupTopic;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 群组事件MQ消费
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = Topics.GROUP_COMMAND, consumerGroup = "COMMAND")
public class GroupConsumerListener implements RocketMQListener<MessageExt> {
    private final List<CommandHandler<GroupTopic, Group>> groups;

    @Override
    public void onMessage(MessageExt message) {
        String serial = new String(message.getBody());
        log.debug("收到MQ消息：{}", serial);
        GroupTopic topic = JSONUtil.parseObj(serial).toBean(GroupTopic.class);
        boolean b = groups.stream().anyMatch(e -> e.invoke(topic));
        log.debug("命令执行{}: {}", b ? "成功" : "失败", topic.getOperation());
    }
}
